import React from 'react';
import { Tree, Button } from 'antd';
import FlodCloseSvg from './images/fold-close.svg';
import _ from 'lodash';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { actions as assetManageActions, TreeSelectFilterType } from '../../reducer';
import PropTypes from 'prop-types';
import './index.less';

function formatTreeData(data = [], belong = {}, level = 1) {
  const treeData = [];
  let index = 1;
  for (const item of data) {
    if (!item.name) {
      continue;
    }
    item.belong = _.isEmpty(belong) ? _.pick(item, ['_id', 'name']) : belong;
    const option = {
      title: (
        <>
          <span className="name" title={item.name}>
            {item.name}
          </span>
          <span className="count">{item.count}</span>
        </>
      ),
      item: item,
      value: item.count,
      key: `${item._id || item.name}_${level}_${index}`,
      icon: level === 1 ? <img src={FlodCloseSvg} /> : null
    };

    if (item.children) {
      option.children = formatTreeData(item.children, item.belong, level + 1);
    }

    treeData.push(option);
    index++;
  }

  return level > 1 ? _.sortBy(treeData, 'value').reverse() : treeData;
}

class CustomAttributeFilter extends React.Component {
  static propTypes = {
    assetStats: PropTypes.object,
    attributeFilter: PropTypes.object,
    setState: PropTypes.func,
    role: PropTypes.string
  };
  constructor(props) {
    super(props);
    this.state = {
      expandedKeys: []
    };
  }

  onSelectKey = (selectKeys, e) => {
    const key = _.get(e, 'node.props.eventKey');
    if (!key) {
      return;
    }

    const nodeItem = _.get(e, 'node.props.item', {});
    const isLeafNode = !_.get(nodeItem, 'children.length');

    if (isLeafNode) {
      // 叶子节点点击筛选
      const belong = nodeItem.belong;
      if (_.isEmpty(belong)) {
        return;
      }
      const { attributeFilter, setState } = this.props;
      const attributeId = `CUSTOM_ATTRIBUTE_${belong._id}`;
      const newAttributeFilter = _.cloneDeep(attributeFilter);
      const preMoreActionValue = _.get(newAttributeFilter, ['moreAction', 'value'], []);
      if (!_.map(preMoreActionValue, 'value').includes(attributeId)) {
        newAttributeFilter.moreAction = {
          type: TreeSelectFilterType,
          value: preMoreActionValue.concat({
            label: belong.name,
            value: attributeId
          })
        };
      }
      newAttributeFilter[attributeId] = {
        type: TreeSelectFilterType,
        value: [
          {
            label: nodeItem.name,
            value: nodeItem._id
          }
        ]
      };
      setState({
        attributeFilter: newAttributeFilter,
        pagaition: {
          page: 1,
          pageSize: 10
        }
      });
    } else {
      // 父节点展开
      const { expandedKeys } = this.state;
      if (_.includes(expandedKeys, key)) {
        this.setState({
          expandedKeys: expandedKeys.filter(k => k !== key)
        });
      } else {
        this.setState({
          expandedKeys: expandedKeys.concat(key)
        });
      }
    }
  };

  onExpand = expandedKeys => {
    this.setState({ expandedKeys });
  };

  renderEmpty = () => {
    if (this.props.role !== '安全管理员') {
      return null;
    }
    return (
      <div className="custom-attribute-tree">
        <div className="empty-desc">还未创建资产属性</div>
        <div className="conf-btn-wrapper">
          <Button className="conf-btn" type="default">
            <a href="/asset-config/attribute-config">去配置</a>
          </Button>
        </div>
      </div>
    );
  };

  render() {
    const { assetStats = {} } = this.props;
    const { customAttribute = [] } = assetStats;

    const { expandedKeys } = this.state;

    if (_.isEmpty(customAttribute)) {
      return this.renderEmpty();
    }

    return (
      <div className="custom-attribute-tree">
        <Tree
          showIcon
          expandedKeys={expandedKeys}
          onSelect={this.onSelectKey}
          onExpand={this.onExpand}
          treeData={formatTreeData(customAttribute)}
        />
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    assetStats: _.get(state, 'assetManage.assetStats', {}),
    attributeFilter: _.get(state, 'assetManage.attributeFilter', {}),
    role: _.get(state, 'auth.user.role', '')
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(assetManageActions, dispatch)
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CustomAttributeFilter);
